package com.arvin.controller;

import com.arvin.pojo.Result;
import com.arvin.pojo.User;
import com.arvin.service.EmailService;
import com.arvin.service.UserService;
import com.arvin.utils.JwtUtil;
import com.arvin.utils.Md5Util;
import com.arvin.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/user")
@Tag(name = "用户登录接口文档",description = "用户登录接口文档")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate redisTemplate;

    private String codes;
    //注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        System.out.println(user.getEmail());
        String code = (String) redisTemplate.opsForValue().get(user.getEmail());
        System.out.println(code);
        if (user.getStudentId().length()==12&&user.getPassword()!=null){
            //判断用户名是否已存在
            User u = userService.findByUsername(user.getStudentId());
            if(u==null&&code.equals(user.getCode())){
                userService.register(user.getStudentId(), user.getPassword(),user.getEmail());
                redisTemplate.delete(user.getEmail());
                return Result.success();
            }else return Result.error("用户名存在");

        }
        else return Result.error("操作失败");
    }
    //发送邮箱
    @PostMapping("/sendMsg")
    public Result send(@RequestBody User user){
        //收件人信息
        String to = user.getEmail();
        //邮件标题
        String title = "【卓越班报名平台】 邮箱验证码";
        //邮箱正文
        codes = "";
        Random r=new Random();
        //2.定义一个for循环，随机n次，随机生成字符
        for(int i=0;i<4;i++) {
            //3.生成随机字符，可能是数字，大写字母，小写字母
            int num = r.nextInt(3);
            switch (num) {
                case 0:
                    //数字:0-9
                    codes += r.nextInt(10);
                    break;
                case 1:
                    //大写字母:A(65)-Z(65+25)
                    char ch1 = (char) (r.nextInt(26) + 65);
                    codes += ch1;
                    break;
                case 2:
                    //小写字母:a(97)-z(97+25)
                    char ch2 = (char) (r.nextInt(26) + 97);
                    codes += ch2;
                    break;
            }
        }
        redisTemplate.opsForValue().set(user.getEmail(),codes,5, TimeUnit.MINUTES);
        System.out.println(codes);
        String context = "验证码："+codes+"，邮箱验证码5分钟内有效【湘信卓越班】";
        //发送邮箱
        boolean flag = emailService.send(to,title,context);
        if (flag){
            return Result.success();
        }
        return Result.error("验证码发生错误");
    }
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        //通过用户名查找
        User userlogin = userService.findByUsername(user.getStudentId());
        //判断是否存在
        if (userlogin == null){
            return Result.error("学号不存在");
        }
        if (Md5Util.getMD5String(user.getPassword()).equals(userlogin.getPassword())){
            //用户名密码匹配登陆成功
            //jWT令牌获取
            Map<String,Object> claims = new HashMap<>();
            claims.put("StudentId",userlogin.getStudentId());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }
    //重置密码
    @PostMapping("/reset")
    public Result reset(@RequestBody User user){
        User user1 = userService.findByUsername(user.getStudentId());
        if (user.getEmail().equals(user1.getEmail())){

            String code = (String) redisTemplate.opsForValue().get(user.getEmail());
            if (!StringUtils.hasLength(user.getStudentId()) || !StringUtils.hasLength(user.getEmail())
                    ||!StringUtils.hasLength(user.getPassword()) || !StringUtils.hasLength(user.getConfirmPassword())
                    || !StringUtils.hasLength(user.getCode())){
                return Result.error("缺少必要的参数");
            }
            if (!user.getPassword().equals(user.getConfirmPassword())){
                return Result.error("两次密码填写不一样");
            }
            if (!user.getCode().equals(code)){
                return Result.error("验证码错误");
            }
            userService.updatePwd(user.getPassword(),user.getStudentId());
            redisTemplate.delete(user.getEmail());
            return Result.success("密码修改成功");
        }

        return Result.error("邮箱或学号错误");
    }
    //修改密码
    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody User user) {
        if (!StringUtils.hasLength(user.getPassword()) || !StringUtils.hasLength(user.getNewPassword()) || !StringUtils.hasLength(user.getConfirmPassword())) {
            return Result.error("缺少必要的参数");
        }
        Map<String,Object> map = ThreadLocalUtil.get();
        String studentId = (String) map.get("StudentId");
        User loginUser = userService.findByUsername(studentId);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(user.getPassword()))){
            return Result.error("原密码填写不正确");
        }
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return Result.error("两次密码填写不一样");
        }
        userService.updatePwd(user.getNewPassword(), studentId);
        return Result.success();

    }
}
